package com.globallogic.strelchuk.usermanager.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.globallogic.strelchuk.usermanager.domain.User;

@Component
public class UserDaoImpl implements UserDao {

	@Autowired
	private SessionFactory sessionFactory;

	@SuppressWarnings("unchecked")
	@Transactional
	public List<User> listAllUsers() {
		return sessionFactory.getCurrentSession().createQuery("from User")
				.list();
	}
	
	@Transactional
	public void addUser(User user) {
		sessionFactory.getCurrentSession().save(user);
	}

	@Transactional
	public void removeUser(Integer id) {
		User user = (User) sessionFactory.getCurrentSession().load(User.class,
				id);
		if (null != user) {
			sessionFactory.getCurrentSession().delete(user);
		}
	}

	@Transactional
	public void editUser(User user, Integer id) {
		User usr = (User) sessionFactory.getCurrentSession().load(User.class,
				id);
		if (null != usr) {
			usr.setLogin(user.getLogin());
			usr.setPassword(user.getPassword());
			usr.setName(user.getName());
			usr.setEmail(user.getEmail());
			usr.setRole(user.getRole());
			usr.setCreatedate(user.getCreatedate());

			sessionFactory.getCurrentSession().update(usr);
		}
	}

	@Transactional
	public User getUserById(Integer id) {
		return (User) sessionFactory.getCurrentSession()
				.createQuery("from User where id=?").setParameter(0, id).list()
				.get(0);
	}

	@Transactional
	public User getUserByLogin(String login) {
		return (User) sessionFactory.getCurrentSession()
				.createQuery("from User where login=?").setParameter(0, login)
				.uniqueResult();
	}

	@Transactional
	public boolean isCorrectPassword(User user) {
		User tmpUser = getUserByLogin(user.getLogin());
		return tmpUser != null
				&& tmpUser.getPassword().equals(user.getPassword());
	}

	@Transactional
	public boolean isUserSignedIn(User user) {
		User tmpUser = getUserByLogin(user.getLogin());
		return tmpUser.isSignin();
	}
}
